//
//  MainViewController.m
//  TestUtilityApplication
//
//  Created by Jeoffrey Thirot on 06/03/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MainViewController.h"

@implementation MainViewController
@synthesize startGameButton = _startGameButton;
@synthesize playerNameTF = _playerNameTF;
@synthesize scrollView = _scrollView;
@synthesize delegateSession = _delegateSession;
@synthesize logLabel = _logLabel;


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    
    CGSize pt = [UIScreen mainScreen].bounds.size;
    self.scrollView.contentSize = CGSizeMake(pt.width, pt.height);
    
    challengerName = [NSString stringWithFormat:@"player2"];
    numPlayer = 0;
    
    _delegateSession = [[BTSession alloc] init];
    [self createPicker];
}

- (void)viewDidUnload
{
    [self setStartGameButton:nil];
    [self setPlayerNameTF:nil];
    [self setScrollView:nil];
    [self setLogLabel:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
    //return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [_startGameButton release];
    [_playerNameTF release];
    [_scrollView release];
    [_logLabel release];
    [challengerName release];
    [super dealloc];
}

#pragma mark - Flipside View

- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)showInfo:(id)sender
{    
    FlipsideViewController *controller = [[[FlipsideViewController alloc] initWithNibName:@"FlipsideViewController" bundle:nil] autorelease];
    controller.delegate = self;
    controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentModalViewController:controller animated:YES];
}

#pragma mark - Method Perso

- (void) createPicker
{
    mPicker = [[GKPeerPickerController alloc] init];
	mPicker.delegate = self.delegateSession;
	//mPicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby | GKPeerPickerConnectionTypeOnline;
    mPicker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
}

- (IBAction)connectingAction:(id)sender {
    
    if( !DEBUG_MODE ) {
        NSLog(@"connectingAction Mode release");
        [self.delegateSession setMyName:self.playerNameTF.text];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connected:) name:kSBConnectedBTSession object:nil];
        //Show the connector
        if( mPicker == nil ) {
            [self createPicker];
        }
        [mPicker show];
    } else {
        NSLog(@"connectingAction Mode debug");
        [self startGameAction];
    }
}

- (void) connected:(NSNotification *)notification
{
    NSLog(@"connected : %@", [notification userInfo]);
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kSBConnectedBTSession object:nil];
    // Remove picker
    mPicker.delegate = nil;
    [mPicker dismiss];
    [mPicker release];
    mPicker = nil;
    
    // Init les data player + player 1 et 2
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataInitGame:) name:kSBReceiveDataFromSession object:nil];
    //NSLog(@"%@", [notification.userInfo objectForKey:@"body"]);
    numPlayer = [[notification.userInfo objectForKey:@"body"] intValue];
    self.logLabel.text = [NSString stringWithFormat:@"player %d", numPlayer];
    //NSLog(@"Init data for peers : %@", self.delegateSession.mPeers);
    // Demande le nom de l'autre joueur
    NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"flag", self.playerNameTF.text, @"playerName", nil];
    [self.delegateSession sendData:data];
}

-(void) dataInitGame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    
    switch ( [[info objectForKey:@"flag"] integerValue] ) {
        case 1:
            NSLog(@"Flag 1 :: %@", info);
            //NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"flag", @"testData2", @"test2", nil];
            challengerName = [[info objectForKey:@"playerName"] retain];
            NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"flag", @"ready", @"state", nil];
            
            [self.delegateSession sendData:data];
            
            break;
        case 2:
            NSLog(@"Flag 2 :: %@", info);
            if( [[info objectForKey:@"state"] isEqualToString:@"ready"] ) {
                [[NSNotificationCenter defaultCenter] removeObserver:self name:kSBReceiveDataFromSession object:nil];
                [self startGameAction];
            }
            
            break;
    
        default:
            break;
    }
    
    
    
}

- (void)startGameAction {
    GameViewController *gameVC = [[GameViewController alloc] initWithNibName:@"GameViewController" bundle:nil];
    
    if( !DEBUG_MODE ) gameVC.delegateBTSession = self.delegateSession;
    [gameVC namePlayer:self.playerNameTF.text andNumPlayer:numPlayer andChallengerName:challengerName];
    [self.navigationController pushViewController:gameVC animated:YES];
    [gameVC release];
}

#pragma mark - UITextFieldDelegate

- (void)keyboardWillShow:(NSNotification *)notification {
    
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSValue* aValue = [userInfo objectForKey:@"UIKeyboardBoundsUserInfoKey"];
    CGSize keyboardSize = [aValue CGRectValue].size;

    
    CGSize pt = [UIScreen mainScreen].bounds.size;
    self.scrollView.contentSize = CGSizeMake(pt.width, pt.height + keyboardSize.height);
    
    flagScroll = 0;
    CGRect rect = CGRectMake( 0, keyboardSize.height, 320, 480);
    [self.scrollView scrollRectToVisible: rect animated:YES];
    
}


- (void)keyboardWillHide:(NSNotification *)notification {
    
    //NSDictionary* userInfo = [notification userInfo];
    
    CGPoint pt = CGPointMake(0, 0);
    flagScroll = 1;
    [self.scrollView setContentOffset:pt animated:YES];
    // La même avec un rect
    //CGRect rect = CGRectMake( 0, 0, 320, 480);
    //[self.scrollView scrollRectToVisible: rect animated:YES];
    
    //CGSize pt2 = [UIScreen mainScreen].bounds.size;
    //self.scrollView.contentSize = CGSizeMake(pt2.width, pt2.height);
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.playerNameTF resignFirstResponder];
    return NO;
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGPoint newLocation = [[touches anyObject] locationInView:self.view];
    NSLog(@"touchesEnded : %f, %f", newLocation.x, newLocation.y);
    [self.playerNameTF resignFirstResponder];
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    //NSLog(@"scrollViewDidEndScrollingAnimation %d", flagScroll );
    CGSize pt;
    
    switch (flagScroll) {
        case 1:
            pt = [UIScreen mainScreen].bounds.size;
            self.scrollView.contentSize = CGSizeMake(pt.width, pt.height);
            //NSLog(@"screen size %f, %f", pt.width, pt.height );
            break;
            
        default:
            break;
    }
}


@end
